package com.inspectortime.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Class that provides basic hash functionality Hash type SHA1
 * 
 * @author bavelar
 * 
 */
public final class HashUtils {

	private static Log log = LogFactory.getLog(HashUtils.class);

	private static final String ENCODING = "UTF8";
	private static final String DIGEST = "SHA1";
	private static final String SECRET = "_*_!A$Z39";

	private HashUtils() {

	}

	/**
	 * Produces a 40-character long hash in hex format
	 * 
	 * @param prop
	 * @return
	 */
	public static String getHash(String prop) {
		String clearText = SECRET + prop;
		String vc = checksum(clearText);
		return vc;
	}

	public static boolean hashOk(String hash, String prop) {
		String cypherText = getHash(prop);
		return hash.equalsIgnoreCase(cypherText);
	}

	private static String checksum(String s) {
		try {
			return toHexString(MessageDigest.getInstance(DIGEST).digest(
					s.getBytes(ENCODING)));
		} catch (NoSuchAlgorithmException e) {
			log.fatal("Unable to get instance of " + DIGEST + " MessageDigest",
					e);
			return "";
		} catch (UnsupportedEncodingException e) {
			log.fatal(ENCODING + " unsupported", e);
			return "";

		}
	}

	private static String toHexString(byte[] b) {
		if (null == b) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		for (int k = 0; b.length > k; ++k) {
			toHex(b[k], sb);
		}
		return sb.toString();
	}

	private static void toHex(byte b, StringBuffer sb) {
		final char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
				'9', 'a', 'b', 'c', 'd', 'e', 'f' };
		int i = (b >> 4) & 0xf;
		sb.append(hexChars[i]);
		i = b & 0xf;
		sb.append(hexChars[i]);
	}

}
